/*
 * Read it Later REST API controller.
 *
 * @author Yves Marcoz
 *
 * Copyright(C) 2011 Yves Marcoz <yvez@marcoz.org>
 * Copyright(C) 2012 Stefan Siegl <stesie@brokenpipe.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

//############ Private functions###################

function getProtocol() {
    if (utility.getPlatform() == "maemo5") {
        return "http://";
    } else {
        return "https://";
    }
}

function fetchArticleTitles(cb) {
    var rs = Storage.getListOfEmptyTitleArticles();

    if (rs.rows.length > 0) {
        for(var i = 0; i < rs.rows.length; i++) {
            var url = rs.rows.item(i).url;
            fetchArticleTitle(url, function() {
                if (cb !== undefined &&
                    Storage.getListOfEmptyTitleArticles().rows.length === 0) {
                    cb();
                }
            });
        }
    } else {
        if (cb !== undefined) {
            cb();
        }
    }
}

function fetchArticleTitle(url, cb) {
    var xhr = new XMLHttpRequest;

    xhr.open("GET", url);
    xhr.setRequestHeader("Connection", "close");
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            var title = url;  /* fallback to title = URL. */

            if (xhr.status == 200) {
                var res = xhr.responseText.match(/<title>([^<]+)<\/title>/i);
                if (res.length === 2) {
                    title = res[1];
                }
            } else {
                notification.showNotification("Unable to download article.");
            }

            Storage.setRilTitle(url, title);
            articleViewer.refreshList();

            if (cb !== undefined) {
                var rs = Storage.getListOfEmptyTitleArticles();

                if (rs.rows.length === 0) {
                    cb();
                }
            }
        }
    }

    xhr.send();
}

function sendReadArticlesList(cb) {
    var rs = Storage.getListOfReadArticles();

    if (rs.rows.length === 0) {
        cb();
        return;
    }

    var req = {};
    for(var i = 0; i < rs.rows.length; i++) {
        req[i] = { url: url = rs.rows.item(i).url }
    }

    var jreq = JSON.stringify(req);
    var xhr = new XMLHttpRequest;
    var url = getProtocol() + "readitlaterlist.com/v2/send";
    var params = rilGetParams() + "&read=" + jreq;

    xhr.open("POST", url);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            cb();
        }
    }

    xhr.send(params);
}

function rilDownloadAllArticles() {
    var rs = Storage.getListOfDownloadables();

    if (rs.rows.length > 0) {
        for(var i = 0; i < rs.rows.length; i++) {
            var url = rs.rows.item(i).url;
            rilDownloadRilArticle(url);
        }
    } else {
        toolBar.feedUpdating = false;
    }
}

function rilDownloadList() {
    var xhr = new XMLHttpRequest;
    var params = rilGetParams();

    var url = getProtocol() + "readitlaterlist.com/v2/get";
    var since = Storage.getSetting("rilLastUpdate");
    if (since === "Unknown") {
        /* So far we've never retrieved the article list, therefore get all unread articles. */
        params = params + "&state=unread"
    } else {
        /* We're getting all articles since last update.  Don't set state=unread filter,
         * since we wouldn't notice (externally caused) unread->read transitions otherwise. */
        params = params+"&since="+since;
    }

    xhr.open("POST", url);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status == 200) {
                Storage.setSetting("rilList",xhr.responseText);
                var parsed = JSON.parse(xhr.responseText);

                var a = parsed["list"];
                for (var b in a) {
                    var o = a[b];

                    if(o.url.substr(0, 75) === o.title) {
                        /* If title equals url, let's try to do better and
                           fetch the page title later on.
                           Pocket currently cuts the title to 75 chars. */
                        o.title = "";
                    }

                    Storage.saveRilArticle(o.url, o.title, "Not downloaded yet", o.state);
                    articleViewer.refreshList();
                }

                sendReadArticlesList(function() {
                    Storage.removeReadArticles();
                    articleViewer.removeReadArticles();

                    fetchArticleTitles(rilDownloadAllArticles);
                });

                Storage.setSetting("rilLastUpdate", parsed["since"]+"");
            } else {
                if (xhr.status == 401) {
                    notification.showNotification("Invalid username or password.");
                } else {
                    notification.showNotification("Error downloading Read It Later list.")
                }
                toolBar.feedUpdating = false;
            }
        }
    }
    xhr.send(params);
}

function rilDownloadRilArticle(articleUrl) {
    var xhr = new XMLHttpRequest;

    var params = "apikey=" + Storage.getSetting("apikey")+"&images=1&url="+articleUrl;
    var url= getProtocol() + "text.readitlaterlist.com/v2/text";
    xhr.open("POST", url);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");

    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            Storage.updateRilArticle(articleUrl,'<html><head></head><body bgcolor="#ffffff">'
                                     +'<table style="border: 1px solid darkblue; width: 100%; background-color: lightgrey">'
                                     +'<tr><td>'
                                     +'<a href="'+articleUrl+'">'+Storage.getRilTitle(articleUrl)+'</a>'
                                     +'</td></tr>'
                                     +'</table>'
                                     +xhr.responseText+'</body></html>');

            if (Storage.getListOfDownloadables().rows.length == 0) {
                toolBar.feedUpdating = false;
            }
        }
    }

    xhr.send(params);
}

function rilDownloadApiKey() {
    var xhr = new XMLHttpRequest;
    var url = "http://feedingit.marcoz.org/lukija.apikey?platform=" + utility.getPlatform();
    xhr.open("GET", url);

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            Storage.setSetting("apikey", xhr.responseText);
        }
    };

    xhr.send();
}

function rilGetParams() {
    var username = Storage.getSetting("username");
    var password = Storage.getSetting("password");
    var apikey = Storage.getSetting("apikey");

    if (apikey === "Unknown") {
        rilDownloadApiKey();
    }

    return "username=" + username + "&password=" + password + "&apikey=" + apikey;
}

//########## End Of Private Functions #######

//###### Read It Later API ###########
function rilGet(listmodel) {
    // Get the list of articles in the RIL account, and add it to a ListModel object
    Storage.getRilList(listmodel);

    return listmodel;
}

function updateList() {
    rilDownloadList();
}

//######### End of API #########
